<!--
 * @Author: cgl
 * @Date: 2023-04-18 15:12:26
 * @LastEditors: cgl
 * @LastEditTime: 2023-08-24 10:26:27
 * @FilePath: \public-health-emergencies-fed:\radiation-hygiene-fe\src\views\slide\inspect.vue
 * @Description:
 *
 * Copyright (c) 2023 by cgl/微盛信息产业有限公司, All Rights Reserved.
-->
<template>
  <div class="app-container">
    <el-form
      class="searchform"
      :model="queryParams"
      ref="queryParams"
      size="small"
      label-width="100px"
    >
      <el-row>
        <el-col :span="4">
          <el-form-item label="单位名称">
            <m-select
              v-model="queryParams.entrustOrganizationId"
              placeholder="输入文字检索查询"
              style="width: 100%"
              filterable
              clearable
              :lists="organizationList"
              lists_label="organizationName"
              lists_value="entrustOrganizationId"
              lists_key="entrustOrganizationId"
              :total="orgTotal"
              :pageSize="10"
              @handleChange="listeningEvent"
            >
            </m-select>
          </el-form-item>
        </el-col>
        <el-col :span="9">
          <el-form-item label-width="20px">
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="getList()"
              >搜索</el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="reset()"
              >重置</el-button
            >
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <div class="table-wrapper">
      <div class="operation">
        <el-button
          class="register"
          type="primary"
          size="mini"
          @click="openDialog()"
          >登记</el-button
        >
      </div>

      <el-table
        v-loading="loading"
        :data="detectionList"
        @row-dblclick="(row) => openDialog(row, '3')"
      >
        <el-table-column
          label="单位名称"
          align="center"
          prop="entrustOrganizationName"
          :show-overflow-tooltip="true"
        />
        <el-table-column label="任务要求完成日期" align="center">
          <template slot-scope="{ row }">
            {{ parseTime(row.requireCompletionDate, "{y}/{m}/{d}") }}
          </template>
        </el-table-column>
        <el-table-column
          label="应检测人数"
          align="center"
          prop="shouldCheckCount"
        />
        <el-table-column label="已检测人数" align="center" prop="checkCount" />
        <el-table-column label="检测时间" align="center">
          <template slot-scope="{ row }">
            {{ parseTime(row.detectionTime, "{y}/{m}/{d}") }}
          </template>
        </el-table-column>
        <el-table-column label="检测登记起止时间" align="center">
          <template slot-scope="{ row }">
            {{ parseTime(row.wearingBeginTime, "{y}/{m}/{d}") }} -
            {{ parseTime(row.wearingEndTime, "{y}/{m}/{d}") }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="100px">
          <template slot-scope="{ row }">
            <el-button @click.native.prevent="openDialog(row, '2')" type="text">
              编辑
            </el-button>

            <el-button
              type="text"
              v-if="row.shouldCheckCount > row.checkCount"
              @click.native.prevent="taskRegister(row)"
            >
              登记
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <!-- 登记弹框 -->
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      @closed="closeExam"
      width="1200px"
      v-dialogDrag="true"
    >
      <div class="searchcontainer">
        <el-upload
          ref="upload"
          class="myupload"
          :action="upload.url"
          :headers="upload.headers"
          :data="upload.data"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          :on-success="handleFileSuccessSecond"
          :auto-upload="true"
          :before-upload="beforeAvatarUpload"
          :show-file-list="false"
          v-if="status == '1'"
        >
          <el-button
            class="uploadbutton"
            icon="el-icon-upload"
            size="mini"
            type="primary"
            >导入</el-button
          >
        </el-upload>

        <el-form
          class="myform"
          :model="form"
          :disabled="status == '3'"
          ref="form"
          :rules="rules"
          size="small"
          label-width="100px"
        >
          <el-form-item label="检测设备" prop="equipmentId">
            <el-select
              v-model="form.equipmentId"
              placeholder="输入文字检索查询"
              size="mini"
              :disabled="status == '3'"
              filterable
              @change="changeEquipment"
              clearable
            >
              <el-option
                :label="'(' + item.equipmentNumber + ')' + item.equipmentName"
                :value="item.equipmentId"
                v-for="(item, index) in equipmentSelect"
                :key="index"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>

        <div class="environment" v-if="status == '1'">
          <span> {{ environment.temperature }}℃</span>
          <span class="humidity">{{ environment.humidity }}%RH</span>
        </div>
      </div>

      <el-table
        :data="importDataList"
        :row-class-name="tableRowClassName"
        height="550"
      >
        <el-table-column label="姓名" align="center" prop="personnelName">
          <template slot-scope="scope">
            <span>{{ scope.row.personnelName }}</span>
            <span v-if="scope.row.dosageType == 1">(内)</span>
            <span v-if="scope.row.dosageType == 2">(外)</span>
          </template>
        </el-table-column>
        <el-table-column
          label="单位名称"
          align="center"
          prop="entrustOrganizationName"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="剂量元件码"
          align="center"
          prop="slidesNumber"
        />
        <el-table-column
          label="检测时间"
          align="center"
          prop="detectionTime"
          width="160"
        />
        <el-table-column label="读出值1" align="center" prop="holeOne" />
        <el-table-column label="系数1" align="center">
          <template slot-scope="{ row }">
            {{ (row.holeOneCoefficient * 100).toFixed(2) }}%
          </template>
        </el-table-column>
        <el-table-column label="读出值2" align="center" prop="holeTwo" />
        <el-table-column label="系数2" align="center">
          <template slot-scope="{ row }">
            {{ (row.holeTwoCoefficient * 100).toFixed(2) }}%
          </template>
        </el-table-column>
        <el-table-column
          label="剂量当量(mSv)"
          align="center"
          prop="dosageValue"
        />
        <el-table-column v-if="status == '1'" align="center" label="操作">
          <template slot-scope="scope">
            <el-button
              @click.native.prevent="deleteData(scope.$index)"
              type="text"
              style="color: #f32d2d"
              size="mini"
            >
              删除
            </el-button>
            <el-button
              @click.native.prevent="handleException(scope.row)"
              type="text"
              size="mini"
              v-if="largeDose && scope.dosageValue > largeDose"
            >
              异常报备
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer">
        <el-button @click="dialogVisible = false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 环境条件弹框 -->
    <el-dialog
      title="环境条件"
      :visible.sync="environmentVisible"
      :close-on-click-modal="false"
      width="550px"
      class="eviromentDialog"
      v-dialogDrag="true"
      :show-close="false"
    >
      <el-form
        :model="formEnvironment"
        :rules="rulesEnvironment"
        ref="formEnvironment"
        size="small"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="温度(℃)" prop="temperature">
              <el-input
                v-model="formEnvironment.temperature"
                placeholder="请输入"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="湿度(%RH)" prop="humidity">
              <el-input
                v-model="formEnvironment.humidity"
                placeholder="请输入"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div slot="footer">
        <el-button type="primary" @click="submitEnvironment">确 定</el-button>
        <el-button @click="cancelEnvironment">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 登记弹框查看 -->
    <inspect-dialog
      v-if="dialogVisibleView"
      :open="dialogVisibleView"
      :rowData="rowData"
      :status="status"
      :title="title"
      @close="dialogVisibleView = false"
    />
  </div>
</template>

<script>
import {
  slidesSampleListing,
  slidesSampleUpdateState,
} from "@/api/slides/slideSample";
import {
  addExceptionalRecord,
  getConfiglargeDose,
} from "@/api/slides/abnormal";
import { environmentAdd } from "@/api/basicData/environment";
import {
  querydetectionList,
  detectionDdd,
  getEnvironment,
  getSlidesDetectionInfo,
  slidesDetectionList,
  equipmentListingForDosimeter,
  detectionRemove,
} from "@/api/slides/inspect";
import {
  entrustOrganizationListing,
  entrustOrganizationList,
} from "@/api/person/entrustOrganization";
import { getToken } from "@/utils/auth";
import inspectDialog from "./dailog/inspectDialog";
import MSelect from "@/components/mSelect";

export default {
  name: "inspect",
  components: {
    MSelect,
    inspectDialog,
  },
  data() {
    return {
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      total: 0,
      dialogVisibleView: false,
      dialogVisible: false,
      list: [],
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 参数
        data: {
          equipmentId: null,
          taskPersonalDosimeterId: "",
        },
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/biz/slide/detection/importData",
      },
      // 滑片列表
      detectionList: [],
      loading: false,
      title: null,
      // 视图高度
      height: document.documentElement.clientHeight,
      // 导入后获取的数值列表
      importDataList: [],
      // 滑片样品下拉框
      slidesSamplesSelect: [],
      // 环境信息
      environment: {
        temperature: "", // 温度
        humidity: "", // 湿度
      },
      // 检测设备下拉框
      equipmentSelect: [],
      // 单位下拉框
      organizationList: [],
      // 表单参数
      form: {},
      rules: {
        equipmentId: [
          { required: true, message: "检测设备不能为空", trigger: "change" },
        ],
      },
      status: null,
      formEnvironment: {},
      environmentVisible: false,
      rulesEnvironment: {
        temperature: [
          { required: true, message: "温度不能为空", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              if (isNaN(value)) {
                callback(new Error("请输入正确的格式"));
              } else {
                callback();
              }
            },
          },
        ],
        humidity: [
          { required: true, message: "湿度不能为空", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              if (isNaN(value)) {
                callback(new Error("请输入正确的格式"));
              } else {
                callback();
              }
            },
          },
        ],
      },
      // 大剂量标准值
      largeDose: null,
      // 是否为管理员
      isAdmin: false,
      rowData: {},
      // 单位查询数据
      organizationQueryData: {
        organizationName: "", //单位名称模糊查询
        pageNum: 1, //页码
        pageSize: 10, //每页展示的条数
      },
      orgTotal: 0,
    };
  },
  created() {
    this.getList();
    this.getEquipmentListing();
    // 获取大剂量标准值
    this.configlargeDose();
    // 温湿度权限控制(管理员不用添加温度湿度 且不能登记)
    let permissions = this.$store.getters.permissions;
    let found = permissions.find((item) => {
      return item == "*:*:*";
    });
    this.isAdmin = found == "*:*:*";
  },
  methods: {
    taskRegister(row) {
      this.dialogVisible = true;
      this.title = "检测登记";
      this.status = "1";
      this.upload.data.taskPersonalDosimeterId = row.taskPersonalDosimeterId;
    },
    // 获取检测设备下拉框
    getEquipmentListing() {
      equipmentListingForDosimeter().then((response) => {
        this.equipmentSelect = response.data;
      });
    },
    // 获取大剂量标准值
    configlargeDose() {
      getConfiglargeDose().then((response) => {
        this.largeDose = response.msg;
      });
    },
    // 获取滑片列表
    getList() {
      const queryParams = { ...this.queryParams };
      this.loading = true;
      querydetectionList(queryParams)
        .then((response) => {
          this.detectionList = response.rows;
          this.total = response && response.total;
          this.loading = false;
        })
        .catch((response) => {
          this.loading = false;
        });
    },
    // 获取滑片样品下拉框
    getSlidesSampleSelect() {
      slidesSampleListing().then((response) => {
        this.slidesSamplesSelect = response.data;
      });
    },
    // 获取单位下拉框
    listeningEvent(e) {
      let { queryName, pageNum, pageSize, type } = e;
      if (type == "scroll" && pageNum == this.organizationQueryData.pageNum)
        return;
      this.organizationQueryData.organizationName = queryName;
      this.organizationQueryData.pageNum = pageNum;
      this.organizationQueryData.pageSize = pageSize;
      entrustOrganizationList(this.organizationQueryData).then((response) => {
        if (type == "scroll") {
          this.organizationList.push(...response.rows);
        } else {
          this.organizationList = response.rows;
        }
        this.orgTotal = response.total;
      });
    },
    // 列表标红
    tableRowClassName({ row, rowIndex }) {
      if (
        (this.largeDose && row.dosageValue > this.largeDose) ||
        row.exceptional
      ) {
        return "warning-row";
      }
      return "";
    },
    // 打开对话框
    async openDialog(row, status) {
      console.log("子row", row);
      this.importDataList = [];
      if (row) {
        this.status = status;
        if (status == "3") {
          this.title = "查看检测登记";
        } else {
          this.title = "编辑检测登记";
        }
        this.rowData = row;
        this.dialogVisibleView = true;
      } else {
        getEnvironment().then((response) => {
          if (
            response.data &&
            response.data.temperature &&
            response.data.humidity
          ) {
            this.environment = {
              temperature: response.data.temperature,
              humidity: response.data.humidity,
            };
          } else {
            this.environmentVisible = true;
            this.formEnvironment = {};
            this.resetForm("formEnvironment");
          }
        });
        this.upload.data.taskPersonalDosimeterId = "";
        this.dialogVisible = true;
        this.title = "检测登记";
        this.status = "1";
      }
    },
    // 关闭环境弹窗
    cancelEnvironment() {
      this.environmentVisible = false;
      this.dialogVisible = false;
    },
    // 删除数据
    deleteData(index) {
      this.$modal
        .confirm(`是否确认删除该数据？`)
        .then(() => {
          return detectionRemove(
            this.importDataList[index].taskPersonalResultId
          );
        })
        .then(() => {
          this.$modal.msgSuccess("删除成功");
          this.importDataList.splice(index, 1);
        })
        .finally(() => {});
    },
    // 更改设备
    changeEquipment(val) {
      this.upload.data.equipmentId = val;
    },
    // 表单重置
    reset() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
      };
      this.resetForm("queryParams");
      this.getList();
    },
    // 提交温度
    submitEnvironment() {
      this.$refs["formEnvironment"].validate((valid) => {
        if (!valid) return;
        environmentAdd(this.formEnvironment).then((response) => {
          this.$modal.msgSuccess("保存成功");
          this.environmentVisible = false;
          this.openDialog();
        });
      });
    },
    // 上传前格式校验
    beforeAvatarUpload(file) {
      console.log("上传前格式校验file", file);
      const isTxt = file.type === "text/plain";

      if (!isTxt) {
        this.$message.warning("请上传txt格式的文件!");
        return false;
      }
      if (!this.form.equipmentId) {
        this.$message.warning("请选择检测设备!");
        return false;
      }
      return true;
    },
    // 文件移除
    handleRemove(file, fileList) {
      this.fileList = fileList;
      this.importDataList = [];
    },
    // 点击文件预览
    handlePreview(file, fileList) {},
    // 超出数量提示
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件`);
    },
    // 文件上传成功处理
    handleFileSuccessSecond(response, file, fileList) {
      if (response.code == 500) {
        this.$modal.msgError(response.msg);
        return;
      }
      if (response.data && response.data.length != 0) {
        this.importDataList.push(...response.data);
      }
      this.fileList = fileList;
      this.upload.open = false;
      this.upload.isUploading = false;
    },
    // 关闭
    closeExam() {
      this.getList();
      if (this.status == "1") {
        this.$refs.upload.clearFiles();
      }
      this.resetForm("form");
      this.form = {};
    },
    // 异常报备
    handleException(row) {
      this.$modal.confirm(`确定异常报备吗？`).then(() => {
        addExceptionalRecord({
          taskPersonalResultId: [row.taskPersonalResultId],
          exceptionType: 2,
        }).then((response) => {
          this.$modal.msgSuccess("报备成功");
        });
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.app-container {
  display: flex;
  flex-direction: column;
}

.operation {
  margin-bottom: 20px;
  .register {
    padding-inline: 30px;
  }
}
.uploadbutton {
  padding-inline: 20px;
}
.result {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 30px;
  .calc {
    width: min-content;
    margin-left: 20px;
    .el-button {
      margin: 0;
      &:nth-of-type(1) {
        margin-bottom: 10px;
      }
    }
  }
}
.nametitle {
  text-align: center;
  margin-bottom: 10px;
  font-weight: bolder;
  &::before {
    content: "* ";
    color: red;
  }
}
::v-deep .el-table .warning-row {
  color: red;
}
.searchcontainer {
  margin-bottom: 20px;
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  .myform {
    height: 30px;
    margin: 0 auto 0 0;
  }
  .environment {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-left: 16px;
    margin-right: 10px;
    font-size: 16px;
    font-weight: bolder;
    margin-top: 10px;
    .humidity {
      transform: translateY(1px);
      margin-left: 20px;
    }
  }
}
.viewform {
  justify-content: flex-end;
}
.eviromentDialog ::v-deep .el-dialog__body .el-form {
  margin-left: -20px;
}
</style>
